import jwt, { JwtPayload } from "jsonwebtoken";
import { config } from "../config";

const sign = (data: any) => {
  return jwt.sign(data, config.auth_msg, { expiresIn: "1d" });
};
const refreshSign = (data: any) => {
  return jwt.sign(data, config.reauth_msg, { expiresIn: "30d" });
};
type SIGNPARAMS = {
  code: number;
  data?: any | JwtPayload;
};
const verify = (token: string): SIGNPARAMS => {
  if (!token) {
    return {
      code: 401,
      data: "无token",
    };                                                                                            
  }
  try {
    let res = jwt.verify(token, config.auth_msg);
    if (res) {
      return {
        code: 200,
        data: res,
      };
    } else {
      return {
        code: 401,
        data: "token过期或错误",
      };
    }
  } catch (error) {
    return {
      code: 401,
      data: "验签失败",
    };
  }
};
const resVerify = (token: string): SIGNPARAMS => {
  if (!token) {
    return {
      code: 401,
      data: "无token",
    };
  }
  try {
    let res = jwt.verify(token, config.reauth_msg);
    if (res) {
      return {
        code: 200,
        data: res,
      };
    } else {
      return {
        code: 401,
        data: "token过期或错误",
      };
    }
  } catch (error) {
    return {
      code: 401,
      data: "验签失败",
    };
  }
};
export { sign, verify, refreshSign, resVerify };
